//引进vue
import Vue from 'vue';
//引进resource插件并定义城对象
import VueResource from 'vue-resource'
//引进本地字典——谢哥的接口
import dictionary from './dictionary_quote.json'
import model from  './model.json'
Vue.use(VueResource)
Vue.http.options.emulateJSON = true
Vue.http.options.emulateHTTP = true
//定义数据接口

const API_ENV = true;
var test = '1';
//true 为正式版 ，false 为测试版
const API_ROOT_DEV = 'http://bmptst.aoyunsoft.com/openapi'
const API_ROOT_RELEASE = 'http://bmp.aoyunsoft.com/openapi'
const API_ROOT = API_ENV ? API_ROOT_RELEASE : API_ROOT_DEV;

Vue.http.interceptors.push(function(request, next) {
  //if(request.url.indexOf('login') == -1){
    //request.params.access_token = JSON.parse(sessionStorage.operation).token
  //}
  next(function(response) {
  });
});
const API = {
  //获取字典
  dictionary:API_ROOT + '/sysmanage/commonCode/formatByGroupCode?_debug=' + test,
}

//queryDictionary
function requestDictionary() {
  Vue.http.post(API.dictionary).then(res => {
    var DICTIONARY = Object.assign(dictionary, JSON.parse(res.body.data))
    if(window.localStorage) {
      window.localStorage.DICTIONARY = JSON.stringify(DICTIONARY)
    }
  })
};
// requestDictionary()
function QueryDictionary(oldkey,str,outStr) {
  //findCommon(key)->所有列表
  //findCommon(key，str)->对应的name值
  //key:要查找的字段，str：已知的字段，输出name值,outStr需要输出的key值，默认为name
  var key = model[oldkey]
  if(window.localStorage) {
    var storage = window.localStorage;
    if(storage.DICTIONARY) {
      var resCode = JSON.parse(storage.DICTIONARY)
      if(resCode[key] && str) {
        for(var i = 0; i < resCode[key].length; i++) {
          for(var k in resCode[key][i]) {
            if(resCode[key][i][k] == str) {
              if(outStr) { return resCode[key][i][outStr]; } else { return resCode[key][i].name; }
            }
          }
        }
      } else if(str=='null' || str == ''){
        return '';
      } else {return resCode[key] }
    } else {}

  } else { return false }
}
//方法裸露
export default  {
  requestDictionary,
  QueryDictionary,
}
